package cn.hanna.springcloudalibaba.controller;

import cn.hanna.springcloud.entities.CommonResult;
import cn.hanna.springcloud.entities.Payment;
import cn.hanna.springcloudalibaba.service.PaymentService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author smileha
 * @create 2021-10-22 10:13
 * @description
 */
@RestController
public class CircleBreakerController {
    public static final String SERVICE_URL = "http://cloudalibaba-sentinel-payment-provider";


    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback")   // 没有任何配置
//    @SentinelResource(value = "fallback",fallback = "handleFallback")   // fallback来处理运行时异常的方法
//    @SentinelResource(value = "fallback",blockHandler = "handleBlockException") //blockHandler处理sentinel控制台配置异常
    @SentinelResource(value = "fallback",fallback = "handleFallback",
                                      blockHandler = "handleBlockException",
                                        exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable Long id)
    {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id, CommonResult.class,id);

        if (id == 4) {
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }

        return result;
    }

    public CommonResult<Payment> handleFallback(@PathVariable Long id,Throwable e){
        return new CommonResult<>(444,"运行时异常，fallback处理："+e.getMessage()+"id:"+id,null);
    }

    public CommonResult<Payment> handleBlockException(@PathVariable Long id, BlockException blockException){
        return new CommonResult<>(445,"dashboard-sentinel限流，blockHandler处理："+blockException.getMessage()+"id:"+id,null);
    }

    //================================使用openfeign+sentinel===================================

    @Resource
    private PaymentService paymentService;

    @GetMapping("/consumer/feign/paymentSQL/{id}")
    public CommonResult<Payment> testFeignSentinel(@PathVariable Long id){
        return paymentService.paymentSQL(id);
    }
}
